package pers.lonestar.framework.utils.support.analysis.handler;

import java.math.BigDecimal;

import pers.lonestar.framework.utils.support.contexts.XlsxReadContext;
import pers.lonestar.framework.utils.support.enums.CellDataTypeEnum;
import pers.lonestar.framework.utils.support.exception.ExcelAnalysisException;
import pers.lonestar.framework.utils.support.metadata.CellData;
import pers.lonestar.framework.utils.support.metadata.read.ReadSheet;
import pers.lonestar.framework.utils.support.utils.BooleanUtil;
import pers.lonestar.framework.utils.support.utils.StringUtil;

public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler {
    @Override
    public void endElement(XlsxReadContext xlsxReadContext, ReadSheet readSheet, String name) {
        CellData<?> tempCellData = readSheet.getTempCellData();
        StringBuilder tempData = readSheet.getTempData();
        String tempDataString = tempData.toString();
        CellDataTypeEnum cellType = tempCellData.getType();
        switch (cellType) {
            case STRING:
            case DIRECT_STRING:
            case ERROR:
                tempCellData.setStringValue(tempDataString);
                break;
            case BOOLEAN:
                if (StringUtil.isEmpty(tempDataString)) {
                    tempCellData.setType(CellDataTypeEnum.EMPTY);
                    break;
                }
                tempCellData.setBooleanValue(BooleanUtil.valueOf(tempDataString));
                break;
            case NUMBER:
            case EMPTY:
                if (StringUtil.isEmpty(tempDataString)) {
                    tempCellData.setType(CellDataTypeEnum.EMPTY);
                    break;
                }
                tempCellData.setType(CellDataTypeEnum.NUMBER);
                tempCellData.setNumberValue(BigDecimal.valueOf(Double.parseDouble(tempDataString)));
                break;
            default:
                throw new ExcelAnalysisException("Can not parse and set value");
        }
        setStringValue(xlsxReadContext, readSheet);
        readSheet.getCellDataMap().put(readSheet.getColumnIndex(), tempCellData);
    }

    @Override
    public void characters(XlsxReadContext xlsxReadContext, ReadSheet readSheet, char[] ch, int start, int length) {
        readSheet.getTempData().append(ch, start, length);
    }

    /**
     * 根据单元格字符串模式(InlineString和SharedString)设定字符串值
     *
     * @param xlsxReadContext
     * @param readSheet
     */
    protected abstract void setStringValue(XlsxReadContext xlsxReadContext, ReadSheet readSheet);
}
